package com.r2coding.security.mobile;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.r2coding.constant.Constant;
import com.r2coding.entity.UsersEntity;
import com.r2coding.service.UserService;
import com.r2coding.util.JwtUtil;
import com.r2coding.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 手机验证码登录成功处理器
 *
 * @author: 98k灬
 * @since: 2022/11/05
 * @email: 98k_style@sina.com
 * @公众号: 爪哇Guy灬
 **/
@Slf4j
@Component
public class CustomMobileAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    @Resource
    ObjectMapper objectMapper;

    @Resource
    RedisTemplate redisTemplate;

    @Resource
    UserService userService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException {
        log.info("=============手机号验证码登录成功处理器=============");
        String mobile = (String)authentication.getPrincipal();
        UsersEntity user = userService.findByMobile(mobile);
        String jwt = JwtUtil.createJWT(user.getId());
        redisTemplate.opsForValue().set(Constant.LOGIN_KEY + user.getId(), jwt, Constant.REDIS_EXPIRE_TIME, TimeUnit.HOURS);

        // JWT返回给前端
        response.setContentType("application/json;charset=UTF-8");
        Result ok = Result.ok(jwt);
        String json = objectMapper.writeValueAsString(ok);
        response.getWriter().write(json);
    }
}
